/**
 * 
 */
package com.ideeli.hwz.service;

import static com.ideeli.webextractor.utils.Constants.HWZ_PASS;
import static com.ideeli.webextractor.utils.Constants.HWZ_URL;
import static com.ideeli.webextractor.utils.Constants.HWZ_USER;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import com.ideeli.hwz.domain.HWZProduct;
import com.ideeli.webextractor.dao.ProductDao;
import com.ideeli.webextractor.service.CacheService;

/**
 * @author sa
 *
 */
public class HWZSubmitServiceImpl implements HWZSubmitService
{
	private static final Logger logger = Logger.getLogger(HWZSubmitService.class);
	
	private CacheService cacheService;
	private WebDriver driver;
	private ProductDao productDao;

	@Override
	public void process() throws Exception
	{
		logger.warn("Start Main Process");
		
		initBrowser();
		List<HWZProduct> prodList=getProductUploadList();
		bulidUploadParameters(prodList);
		
//		String title="HP Mini 200-4204tu B6V22PA 25.7 cm (10.1\") LED Netbook - Intel Atom N2800 1.86 GHz - Glossy";
//		String desc="checkout using the link: " +
//				"http://itshop.com.sg/index.php?route=product/product&product_id=" +
//				"3787" +
//				"\n\nFree next business day delivery, net price." +
//				"\n\nBasic specification:\nBacklight Technology: LED\nBluetooth: Yes\nBrand Name: HP\nColour: Glossy Black\nGraphics Controller Manufacturer: Intel\nGraphics Controller Model: GMA 3600\nGraphics Memory Accessibility: Shared\nGreen Compliant: Yes\nHard Drive Capacity: 320 GB\nMaximum Battery Run Time: 10 Hour\nNumber of Cells: 6-cell\nOperating System Architecture: 32-bit\nOperating System: Genuine Windows 7 Starter\nProcessor Manufacturer: Intel\nProcessor Model: N2800\nProcessor Speed: 1.86 GHz\nProcessor Type: Atom\nProduct Family: Mini 200-4200\nProduct Type: Netbook\nScreen Resolution: 1024 x 600\nScreen Size: 25.7 cm (10.1\")\nStandard Memory: 1 GB\nWebcam: Yes\nWeight (Approximate): 1.38 kg\nWi-Fi: Yes";
//		String tags="Netbook, Intel Atom, 200-4204tu B6V22PA, HP";
//		String image="E:\\Users\\sa\\Desktop\\1972204-500x500.jpg";
				
		
		//name==title
		//description=desc
		//tags=comma separate spaces
		//image=sku.jpg
		//price=price
		
//		postOnHWZ("Notebooks & Accessories",title,desc,"444.54",image,tags);
		finish();
		// TODO Auto-generated method stub
		logger.warn("Finished Main Process");
	}
	
	public void bulidUploadParameters(List<HWZProduct> prodList) throws Exception
	{
		
		for(HWZProduct prod: prodList)
		{
			String title=prod.getTitle();
			String desc="checkout using the link: " +
						"http://itshop.com.sg/index.php?route=product/product&product_id=" +
						prod.getProductId() +
			"\nFree next business day delivery." +
			"\nNet price !" +
			"\n"+prod.getDescription();

			String tags=title.replaceAll(" ", ",");
			String category=cacheService.getIngHwzCatMapping(prod.getCategory());
			float price=prod.getPrice();
			String image=cacheService.getActualImagePath()+prod.getImage()+".jpg";
			
			postOnHWZ(category,title,desc,price+"",image,tags);
			Thread.sleep(1000*2);
			
			
		}
		
	}
	
	
	public List<HWZProduct> getProductUploadList() throws Exception
	{
		
		logger.warn("Start getProductUploadList");
		List<String> prodsToUpload=new ArrayList<String>();

		Map<String, List<String>> catProds=productDao.getCategoryProdsWithImages(99999);
		Map<String,Integer> limitMap=cacheService.getCategoryUpperLimit();
		
		for(String cat: catProds.keySet())
		{
			logger.info("cat:"+cat);
			int limitcount=0;
			int upperLimit=2;
			
			if(limitMap.get(cat)!=null)
				upperLimit=limitMap.get(cat);
			
			logger.info("category limit:"+upperLimit);
			for(String prod:catProds.get(cat))
			{
				if(limitcount<=upperLimit)
					break;
				limitcount++;
				logger.info("   "+prod);
				prodsToUpload.add(prod);
			}
		}
		
		logger.info("No of Products to Upload:"+prodsToUpload.size());
		logger.info("Products to Upload:"+prodsToUpload.toString());
		logger.warn("End getProductUploadList");
		
		String inClause=prodsToUpload.toString();
		inClause=inClause.replaceAll("\\[", "(");
		inClause=inClause.replaceAll("]", ")");
		
		List<HWZProduct> hwzProducts=productDao.getHWZProducts(inClause);
		
		return hwzProducts;
	}


	public void postOnHWZ(String classifiedCategory, String title, String desc, String price, String imageFile, String tags) throws Exception {
		
		logger.info("testPostOnHWZ");
		
		logger.info("posting a new add");
		driver.findElement(By.linkText("Post a New Ad")).click();
		
		logger.info("selected category");
		new Select(driver.findElement(By.id("ClassifiedCategory"))).selectByVisibleText(classifiedCategory);
		
		logger.info("Title");
		driver.findElement(By.id("ClassifiedTitle")).clear();
		driver.findElement(By.id("ClassifiedTitle")).sendKeys(title);

		logger.info("description");
		driver.findElement(By.id("description")).clear();
		driver.findElement(By.id("description")).sendKeys(desc);

		logger.info("price");
		driver.findElement(By.id("ClassifiedPrice")).clear();
		driver.findElement(By.id("ClassifiedPrice")).sendKeys(price);
		
		logger.info("uploading file");
		driver.findElement(By.id("MediaUploadedFiles")).sendKeys(imageFile);
		
		logger.info("tagging");
		driver.findElement(By.id("ClassifiedTags")).clear();
		driver.findElement(By.id("ClassifiedTags")).sendKeys(tags);
		
		logger.info("submit");
		driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
		
		logger.warn("Product submitted");
	}
	
	private void initBrowser() throws Exception
	{
		logger.info("setUP");
		
		logger.warn("initBrowser()..");
		File fExeFile = new File("C:\\Users\\spaida\\c\\f12\\firefox.exe");
		if(fExeFile.exists())
		{
			FirefoxBinary fireFoxBinary = new FirefoxBinary(fExeFile);
			driver = new FirefoxDriver(fireFoxBinary, null);
		}
		else
		{
			driver = new FirefoxDriver();
		}
		
		String baseUrl = cacheService.getAppProperty(HWZ_URL);
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		logger.info("Finished setup");
		
		driver.get(baseUrl + "/home");
		driver.findElement(By.id("login-link")).click();
		driver.findElement(By.xpath("(//input[@id='vb_login_username'])[2]")).clear();
		driver.findElement(By.xpath("(//input[@id='vb_login_username'])[2]")).sendKeys(cacheService.getAppProperty(HWZ_USER));
		driver.findElement(By.xpath("(//input[@id='vb_login_password'])[2]")).clear();
		driver.findElement(By.xpath("(//input[@id='vb_login_password'])[2]")).sendKeys(cacheService.getAppProperty(HWZ_PASS));
		driver.findElement(By.xpath("(//input[@id='btnLogin'])[2]")).click();
		logger.info("logged in");
		driver.findElement(By.linkText("Market Place")).click();
		logger.info("at market place");
	}
	


	public void finish() throws Exception {
		driver.quit();
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}


	public CacheService getCacheService()
	{
		return cacheService;
	}


	public void setCacheService(CacheService cacheService)
	{
		this.cacheService = cacheService;
	}
	
	public ProductDao getProductDao() {
		return productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}
	/*
	 * Categories
	 * CPU
Casings and Coolers
Digital Cameras &amp; Video Camcorders
Display &amp; Graphics Card
Full &amp; Partial Systems
IT Books
Mainboards
Memory, Flash Drives &amp; Accessories
Mobile Phones &amp; Accessories
Networking
Notebooks &amp; Accessories
Others
Optical Storage
Storage
Office Equipment
Server &amp; Workstation
Software
Speakers
Sound Cards
Home Entertainment
Portable Media Players
Headphones
	 */


}
